package com.studyweb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CORS跨域配置
 * 
 * @author StudyWeb Team
 * @since 1.0.0
 */
@Configuration
public class CorsConfig {

    /**
     * 配置CORS跨域资源共享
     * 允许前端应用从不同域名访问后端API
     * 
     * @return CORS配置源对象
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        
        // 允许特定域名进行跨域调用（开发环境配置）
        configuration.addAllowedOrigin("http://localhost:8000");
        configuration.addAllowedOrigin("http://127.0.0.1:8000");
        configuration.addAllowedOrigin("http://localhost:8001");
        configuration.addAllowedOrigin("http://127.0.0.1:8001");
        configuration.addAllowedOrigin("http://localhost:5173");
        configuration.addAllowedOrigin("http://127.0.0.1:5173");
        configuration.addAllowedOrigin("http://localhost:5174");
        configuration.addAllowedOrigin("http://127.0.0.1:5174");
        configuration.addAllowedOrigin("http://47.112.187.207:16667");
        configuration.addAllowedOrigin("https://bbbde0785491.ngrok-free.app");
        // configuration.addAllowedOrigin("*");
        
        // 允许所有请求头（包括自定义头）
        configuration.addAllowedHeader("*");
        
        // 允许所有HTTP方法（GET、POST、PUT、DELETE等）
        configuration.addAllowedMethod("*");
        
        // 允许发送Cookie和认证信息
        configuration.setAllowCredentials(true);
        
        // 预检请求的缓存时间（3600秒=1小时）
        configuration.setMaxAge(3600L);
        
        // 允许前端访问的响应头（用于JWT认证等）
        configuration.addExposedHeader("Authorization");     // JWT令牌
        configuration.addExposedHeader("Content-Type");      // 内容类型
        configuration.addExposedHeader("X-Requested-With");  // AJAX请求标识
        configuration.addExposedHeader("Accept");            // 接受的内容类型
        configuration.addExposedHeader("Origin");            // 请求来源
        configuration.addExposedHeader("Access-Control-Request-Method");  // 预检请求方法
        configuration.addExposedHeader("Access-Control-Request-Headers"); // 预检请求头
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        
        return source;
    }

    /**
     * 创建CORS过滤器Bean
     * 将CORS配置应用到Spring Security过滤器链中
     * 
     * @return CORS过滤器实例
     */
    @Bean
    public CorsFilter corsFilter() {
        return new CorsFilter(corsConfigurationSource());
    }

    @Bean
    public OncePerRequestFilter corsLoggingFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                String origin = request.getHeader("Origin");
                System.out.println("Request Origin: " + origin);
                filterChain.doFilter(request, response);
                System.out.println("Response Access-Control-Allow-Origin: " + response.getHeader("Access-Control-Allow-Origin"));
            }
        };
    }
}